<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/Carousel.css">
</head>
<body>
    <div>
    <!-- 导航点 -->
    <ul id="nav">
        <li class="active"></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
    <!-- 轮播图 -->
    <ul id="img">
        <div class="imgbox">
            <li><img src="./image/01.png" alt=""></li>
            <li><img src="./image/02.png" alt=""></li>
            <li><img src="./image/03.png" alt=""></li>
            <li><img src="./image/04.png" alt=""></li>
        </div>
    </ul>
</div>
</body>
<script>
    var nav = document.getElementById("nav")
    var lis = nav.getElementsByTagName("li")
    var imgbox = document.getElementsByClassName("imgbox")[0]
    var ban = imgbox.getElementsByTagName("li")
    var time = null  ;  //全局变量 -> 记录计时器的编号,方便清除
    var ind = 0;  //记录轮播的下标 (默认显示第一张:0)
    var imgW = ban[0].clientWidth       // 400
    var imgboxW = imgbox.clientWidth    // 1600

    timeChange();

    // 导航点点击 (点击切换)
    for(var i = 0; i < lis.length; i++){
        lis[i].dataset.index = i
        lis[i].onclick = function(){
            // 点 =>效果切换
            for(var j = 0; j < lis.length; j++){
                lis[j].classList.remove("active")
            }
            this.classList.add("active")

            // 先清除原本的轮播 在开启新的(新的计时器2s后执行)
            clearInterval(time)
            timeChange()

            // 在切图片
            ind = this.dataset.index
            nextImg()

        }
    }

    // 延时切换 (轮播切换 -> 设置计时器 每隔2s切换一张)
    function timeChange (){
        time = setInterval(function(){
            ind++
            if(ind >= ban.length){
                ind = 0
            }
            for(var i = 0; i < lis.length; i++){
                lis[i].classList.remove("active")
            }
            lis[ind].classList.add("active")
            nextImg(ind)
        },2000)
    }
    

    // 图片切换 (依赖于 ind)  => 1. 点击导航切图片  2.  轮播切换
    function nextImg(){
        var left = imgW * ind
        if(left > imgboxW - imgW){
            left = 0
        }
        imgbox.style.left = -left + "px"
    }
</script>
</html>